<?php
/**
 * Created by PhpStorm.
 * User: Inhere
 * Date: 2016/4/10 0010
 * Time: 16:04
 */

namespace app\controllers\admin;

use Slim;
use app\extensions\DataEnum;
use app\models\Users;

/**
 * Class Register
 * @package app\controllers\admin
 */
class Register extends Base
{
    /**
     * register
     * @method GET
     * @api /account/register
     *
     * @return Response
     */
    public function registerAction()
    {
        if ( Slim::$app->user->isLogin() ) {
            return redirect_to( Slim::config()->get('urls.afterLoginTo', '/') );
        }

        if ( $this->request->isPost() ) {
            return $this->deRegister();
        }

        return $this->renderTwig('register');
    }

    /**
     * register
     * @method POST
     * @api /account/register
     *
     * @return Response
     */
    private function deRegister()
    {
        $inputs = $this->request->getParams();
        $user = new Users($inputs);
        $type = 'danger';
        $url = '/register';

        if ( ($msg = $user->register()) === true ) {
            $type = 'success';
            $url = '/register-success?id='.$user->id;
        }

        // Redirect and page alert message
        return $this->response->withRedirect($url)->withMessage(['type' => $type, 'msg' => $msg]);
    }

    public function successAcction(Request $req, Response $res)
    {
        $viewVar = [];

        $user = Users::findByPk($req->getInt('id'));

        return $this->renderTwig('success', $res, $viewVar);
    }

    /**
     * forgetPasswd
     * @method GET
     * @api /account/forgetPasswd
     *
     * @return Response
     */
    public function forgetPasswdAction()
    {
        if ( Slim::get('user')->isLogin() ) {
            return redirect_to( Slim::get('config')->get('mder.afterLoginTo', '/') );
        }

        if ( $this->request->isPost() ) {
            return $this->deSendEmail();
        }

        return $this->renderTwig('forget-passwd');
    }

    const RESET_BY_EMAIL = 1;
    const RESET_BY_PHONE = 2;

    /**
     * Reset Passwd by email
     * @method POST
     * @api /forgetPasswd
     *
     * @return Response
     */
    private function deSendEmail()
    {
        $type = $req->getInt('type', self::RESET_BY_EMAIL);

        if ( $type == self::RESET_BY_EMAIL ) {
            # code...
        } elseif (condition) {
            # code...
        }
    }

    /**
     * Reset Passwd by email
     * @method POST
     * @api /account/forgetPasswd
     *
     * @return Response
     */
    private function deResetPasswd()
    {
        # code...
    }
}